package common

import (
	"crypto/md5"
	"encoding/base64"
	"github.com/gogf/gf/g/os/gtime"
	"time"

	"github.com/dgrijalva/jwt-go"
)



type Claims struct {
	//Appid string `json:"appid"`
	// recommended having
	User_id string `json:"user_id"`
	Expire int64 `json:"expire"`
	jwt.StandardClaims
}

func base64Encode(src []byte) []byte {
	return []byte(base64.StdEncoding.EncodeToString(src))
}
func To_md5(encode string) (decode string) {
	md5Ctx := md5.New()
	md5Ctx.Write([]byte(encode))
	cipherStr := md5Ctx.Sum(nil)
	return string(base64Encode(cipherStr))
}

func Create_token(appid string, secret string) (string, int64) {
	expireToken := time.Now().Add(time.Hour * 12).Unix()
	claims := Claims{
		User_id:"",
		Expire:gtime.Second()+3600,
		/*jwt.StandardClaims{
			ExpiresAt: gtime.Second()+3600,
			Issuer:    appid,
		},*/
	}

	// Create the token using your claims
	c_token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

	// Signs the token with a secret.
	signedToken, _ := c_token.SignedString([]byte("secret"))

	return signedToken, expireToken
}

func Token_auth(signedToken, secret string) (bool, error) {
	token, err := jwt.ParseWithClaims(signedToken, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(secret), nil
	})
	if token==nil{
		return false, err
	}
	if claims, ok := token.Claims.(*Claims); ok && token.Valid {
		//fmt.Printf("%v %v", claims.Username, claims.StandardClaims.ExpiresAt)
		//fmt.Println(reflect.TypeOf(claims.StandardClaims.ExpiresAt))
		//return claims.Appid, err
		if claims.Expire<gtime.Second() {
			return false, err
		}
		return true, err
	}
	return true, err
}
